<template>
  <div class="spectrum-analysis">
    <div class="analysis-header">
      <h3>频谱波形分析</h3>
      <div class="header-controls">
        <el-select v-model="selectedSignal" placeholder="选择信号" size="small">
          <el-option label="雷达信号A" value="radar_a" />
          <el-option label="通信信号B" value="comm_b" />
          <el-option label="干扰信号C" value="jam_c" />
        </el-select>
        <el-button type="primary" size="small" @click="startAnalysis">
          {{ analyzing ? '分析中...' : '开始分析' }}
        </el-button>
      </div>
    </div>

    <div class="analysis-content">
      <!-- 频谱分析显示 -->
      <div class="spectrum-display">
        <div class="display-tabs">
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane label="频域分析" name="frequency">
              <div ref="frequencyChart" class="analysis-chart"></div>
            </el-tab-pane>
            <el-tab-pane label="时域波形" name="time">
              <div ref="timeChart" class="analysis-chart"></div>
            </el-tab-pane>
            <el-tab-pane label="时频图" name="spectrogram">
              <div ref="spectrogramChart" class="analysis-chart"></div>
            </el-tab-pane>
            <el-tab-pane label="瀑布图" name="waterfall">
              <div ref="waterfallChart" class="analysis-chart"></div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 分析参数和结果 -->
      <div class="analysis-params">
        <div class="params-section">
          <div class="section-title">分析参数</div>
          <div class="param-row">
            <div class="param-item">
              <span class="param-label">中心频率:</span>
              <span class="param-value">{{ centerFreq }} MHz</span>
            </div>
            <div class="param-item">
              <span class="param-label">采样率:</span>
              <span class="param-value">{{ sampleRate }} MSPS</span>
            </div>
            <div class="param-item">
              <span class="param-label">带宽:</span>
              <span class="param-value">{{ bandwidth }} MHz</span>
            </div>
          </div>
          <div class="param-row">
            <div class="param-item">
              <span class="param-label">FFT点数:</span>
              <span class="param-value">{{ fftPoints }}</span>
            </div>
            <div class="param-item">
              <span class="param-label">窗函数:</span>
              <span class="param-value">{{ windowFunc }}</span>
            </div>
            <div class="param-item">
              <span class="param-label">重叠率:</span>
              <span class="param-value">{{ overlapRatio }}%</span>
            </div>
          </div>
        </div>

        <div class="results-section">
          <div class="section-title">分析结果</div>
          <div class="result-grid">
            <div class="result-item">
              <div class="result-label">峰值频率</div>
              <div class="result-value">{{ peakFreq }} MHz</div>
            </div>
            <div class="result-item">
              <div class="result-label">峰值功率</div>
              <div class="result-value">{{ peakPower }} dBm</div>
            </div>
            <div class="result-item">
              <div class="result-label">平均功率</div>
              <div class="result-value">{{ avgPower }} dBm</div>
            </div>
            <div class="result-item">
              <div class="result-label">信噪比</div>
              <div class="result-value">{{ snr }} dB</div>
            </div>
            <div class="result-item">
              <div class="result-label">占用带宽</div>
              <div class="result-value">{{ occupiedBw }} MHz</div>
            </div>
            <div class="result-item">
              <div class="result-label">调制类型</div>
              <div class="result-value">{{ modType }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// 响应式数据
const activeTab = ref('frequency')
const selectedSignal = ref('radar_a')
const analyzing = ref(false)

// 分析参数
const centerFreq = ref(2450.0)
const sampleRate = ref(100.0)
const bandwidth = ref(20.0)
const fftPoints = ref(1024)
const windowFunc = ref('Hanning')
const overlapRatio = ref(50)

// 分析结果
const peakFreq = ref(2451.2)
const peakPower = ref(-15.6)
const avgPower = ref(-32.4)
const snr = ref(18.7)
const occupiedBw = ref(8.5)
const modType = ref('QPSK')

// 图表引用
const frequencyChart = ref(null)
const timeChart = ref(null)
const spectrogramChart = ref(null)
const waterfallChart = ref(null)

// 图表实例
let chartInstances = {}

// 初始化图表
const initCharts = () => {
  initFrequencyChart()
  initTimeChart()
  initSpectrogramChart()
  initWaterfallChart()
}

// 频域分析图表
const initFrequencyChart = () => {
  if (!frequencyChart.value) return
  
  const chart = echarts.init(frequencyChart.value)
  chartInstances.frequency = chart
  
  const freqData = generateFrequencySpectrum()
  
  const option = {
    backgroundColor: 'rgba(15, 15, 25, 0.8)',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#00f5ff',
      textStyle: { color: '#ffffff' },
      formatter: function(params) {
        const freq = (2430 + params[0].dataIndex * 0.1).toFixed(1)
        const power = params[0].value.toFixed(1)
        return `频率: ${freq} MHz<br/>功率: ${power} dBm`
      }
    },
    grid: {
      left: '8%',
      right: '5%',
      bottom: '15%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: Array.from({length: 200}, (_, i) => (2430 + i * 0.1).toFixed(1)),
      name: '频率 (MHz)',
      nameLocation: 'middle',
      nameGap: 25,
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { 
        color: '#ffffff', 
        fontSize: '0.7vw',
        interval: 19  // 每20个显示一个标签
      },
      axisLine: { lineStyle: { color: '#00f5ff' } },
      splitLine: { show: false }
    },
    yAxis: {
      type: 'value',
      name: '功率 (dBm)',
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { color: '#ffffff', fontSize: '0.7vw' },
      axisLine: { lineStyle: { color: '#00f5ff' } },
      splitLine: { lineStyle: { color: 'rgba(0, 245, 255, 0.3)' } }
    },
    series: [{
      type: 'line',
      data: freqData,
      smooth: false,
      lineStyle: { color: '#00ff00', width: 1 },
      symbol: 'none',
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(0, 255, 0, 0.4)' },
          { offset: 1, color: 'rgba(0, 255, 0, 0.1)' }
        ])
      }
    }]
  }
  
  chart.setOption(option)
}

// 时域波形图表
const initTimeChart = () => {
  if (!timeChart.value) return
  
  const chart = echarts.init(timeChart.value)
  chartInstances.time = chart
  
  const timeData = generateTimeWaveform()
  
  const option = {
    backgroundColor: 'rgba(15, 15, 25, 0.8)',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#00f5ff',
      textStyle: { color: '#ffffff' }
    },
    grid: {
      left: '8%',
      right: '5%',
      bottom: '15%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: Array.from({length: 500}, (_, i) => (i * 0.01).toFixed(2)),
      name: '时间 (ms)',
      nameLocation: 'middle',
      nameGap: 25,
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { 
        color: '#ffffff', 
        fontSize: '0.7vw',
        interval: 49
      },
      axisLine: { lineStyle: { color: '#00f5ff' } },
      splitLine: { show: false }
    },
    yAxis: {
      type: 'value',
      name: '幅度 (V)',
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { color: '#ffffff', fontSize: '0.7vw' },
      axisLine: { lineStyle: { color: '#00f5ff' } },
      splitLine: { lineStyle: { color: 'rgba(0, 245, 255, 0.3)' } }
    },
    series: [{
      type: 'line',
      data: timeData,
      smooth: false,
      lineStyle: { color: '#ffaa00', width: 1 },
      symbol: 'none'
    }]
  }
  
  chart.setOption(option)
}

// 时频图（瀑布图简化版本）
const initSpectrogramChart = () => {
  if (!spectrogramChart.value) return
  
  const chart = echarts.init(spectrogramChart.value)
  chartInstances.spectrogram = chart
  
  const spectrogramData = generateSpectrogramData()
  
  const option = {
    backgroundColor: 'rgba(15, 15, 25, 0.8)',
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#00f5ff',
      textStyle: { color: '#ffffff' }
    },
    grid: {
      left: '8%',
      right: '12%',
      bottom: '15%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: Array.from({length: 50}, (_, i) => `${(2430 + i * 0.4).toFixed(1)}`),
      name: '频率 (MHz)',
      nameLocation: 'middle',
      nameGap: 25,
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { color: '#ffffff', fontSize: '0.7vw' },
      axisLine: { lineStyle: { color: '#00f5ff' } }
    },
    yAxis: {
      type: 'category',
      data: Array.from({length: 30}, (_, i) => `${(i * 0.1).toFixed(1)}`),
      name: '时间 (s)',
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { color: '#ffffff', fontSize: '0.7vw' },
      axisLine: { lineStyle: { color: '#00f5ff' } }
    },
    visualMap: {
      min: -80,
      max: -20,
      calculable: true,
      orient: 'vertical',
      right: '2%',
      top: 'middle',
      textStyle: { color: '#ffffff', fontSize: '0.8vw' },
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffcc', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    series: [{
      name: '功率谱密度',
      type: 'heatmap',
      data: spectrogramData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 245, 255, 0.5)'
        }
      }
    }]
  }
  
  chart.setOption(option)
}

// 瀑布图
const initWaterfallChart = () => {
  if (!waterfallChart.value) return
  
  const chart = echarts.init(waterfallChart.value)
  chartInstances.waterfall = chart
  
  // 这里可以实现3D瀑布图，或者使用线图模拟
  const waterfallData = generateWaterfallData()
  
  const option = {
    backgroundColor: 'rgba(15, 15, 25, 0.8)',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#00f5ff',
      textStyle: { color: '#ffffff' }
    },
    legend: {
      data: ['T1', 'T2', 'T3', 'T4', 'T5'],
      textStyle: { color: '#ffffff', fontSize: '0.8vw' },
      top: '5%'
    },
    grid: {
      left: '8%',
      right: '5%',
      bottom: '15%',
      top: '15%'
    },
    xAxis: {
      type: 'category',
      data: Array.from({length: 100}, (_, i) => (2430 + i * 0.2).toFixed(1)),
      name: '频率 (MHz)',
      nameLocation: 'middle',
      nameGap: 25,
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { 
        color: '#ffffff', 
        fontSize: '0.7vw',
        interval: 9
      },
      axisLine: { lineStyle: { color: '#00f5ff' } }
    },
    yAxis: {
      type: 'value',
      name: '功率 (dBm)',
      nameTextStyle: { color: '#ffffff', fontSize: '0.9vw' },
      axisLabel: { color: '#ffffff', fontSize: '0.7vw' },
      axisLine: { lineStyle: { color: '#00f5ff' } },
      splitLine: { lineStyle: { color: 'rgba(0, 245, 255, 0.3)' } }
    },
    series: waterfallData.map((data, index) => ({
      name: `T${index + 1}`,
      type: 'line',
      data: data,
      smooth: true,
      lineStyle: { 
        width: 1,
        color: `hsl(${index * 60}, 70%, 60%)`
      },
      symbol: 'none'
    }))
  }
  
  chart.setOption(option)
}

// 生成频谱数据
const generateFrequencySpectrum = () => {
  return Array.from({length: 200}, (_, i) => {
    const freq = 2430 + i * 0.1
    let power = -70 + Math.random() * 10
    
    // 添加一些峰值
    if (Math.abs(freq - 2451) < 2) power += 40 * Math.exp(-Math.pow(freq - 2451, 2) / 2)
    if (Math.abs(freq - 2465) < 1) power += 25 * Math.exp(-Math.pow(freq - 2465, 2) / 1)
    
    return Math.round(power * 10) / 10
  })
}

// 生成时域波形数据
const generateTimeWaveform = () => {
  return Array.from({length: 500}, (_, i) => {
    const t = i * 0.01
    return Math.sin(2 * Math.PI * 50 * t) * Math.exp(-t / 2) + 
           0.3 * Math.sin(2 * Math.PI * 120 * t) + 
           0.1 * (Math.random() - 0.5)
  })
}

// 生成时频图数据
const generateSpectrogramData = () => {
  const data = []
  for (let i = 0; i < 30; i++) {
    for (let j = 0; j < 50; j++) {
      const power = -80 + Math.random() * 60
      data.push([j, i, Math.round(power)])
    }
  }
  return data
}

// 生成瀑布图数据
const generateWaterfallData = () => {
  return Array.from({length: 5}, () => 
    Array.from({length: 100}, (_, i) => {
      const freq = 2430 + i * 0.2
      let power = -70 + Math.random() * 10
      if (Math.abs(freq - 2451) < 3) power += 30 * Math.exp(-Math.pow(freq - 2451, 2) / 4)
      return Math.round(power * 10) / 10
    })
  )
}

// 开始分析
const startAnalysis = () => {
  analyzing.value = true
  ElMessage.info('开始频谱分析...')
  
  setTimeout(() => {
    analyzing.value = false
    ElMessage.success('分析完成')
    // 更新分析结果
    updateAnalysisResults()
  }, 2000)
}

// 更新分析结果
const updateAnalysisResults = () => {
  peakFreq.value = (2450 + Math.random() * 10).toFixed(1)
  peakPower.value = (-20 + Math.random() * 10).toFixed(1)
  avgPower.value = (-40 + Math.random() * 10).toFixed(1)
  snr.value = (15 + Math.random() * 10).toFixed(1)
  occupiedBw.value = (8 + Math.random() * 4).toFixed(1)
}

// 监听标签页切换
watch(activeTab, async (newTab) => {
  await nextTick()
  const chartMap = {
    frequency: 'frequency',
    time: 'time',
    spectrogram: 'spectrogram',
    waterfall: 'waterfall'
  }
  
  const chartKey = chartMap[newTab]
  if (chartKey && chartInstances[chartKey]) {
    chartInstances[chartKey].resize()
  }
})

onMounted(async () => {
  await nextTick()
  initCharts()
})

onUnmounted(() => {
  Object.values(chartInstances).forEach(chart => {
    if (chart) chart.dispose()
  })
})
</script>

<style scoped>
.spectrum-analysis {
  height: 35vh;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 1vh;
  padding: 1.5vh 1.5vw;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 245, 255, 0.3);
  display: flex;
  flex-direction: column;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1vh;
  padding-bottom: 1vh;
  border-bottom: 1px solid rgba(0, 245, 255, 0.3);
}

.analysis-header h3 {
  color: #00f5ff;
  font-size: 1.4vw;
  margin: 0;
  text-shadow: 0 0 10px rgba(0, 245, 255, 0.5);
}

.header-controls {
  display: flex;
  gap: 1vw;
  align-items: center;
}

.analysis-content {
  flex: 1;
  display: flex;
  gap: 1vw;
}

.spectrum-display {
  width: 65%;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 0.5vh;
  border: 1px solid rgba(0, 245, 255, 0.2);
}

.analysis-chart {
  height: 20vh;
  width: 100%;
  background: rgba(15, 15, 25, 0.8);
  border-radius: 0.5vh;
}

.analysis-params {
  width: 33%;
  display: flex;
  flex-direction: column;
  gap: 1vh;
  overflow-y: auto;
  max-height: 30vh;
}

.params-section,
.results-section {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 0.5vh;
  padding: 1vh 1vw;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.section-title {
  color: #ffffff;
  font-size: 1.1vw;
  font-weight: bold;
  margin-bottom: 1vh;
  text-align: center;
}

.param-row {
  display: flex;
  flex-direction: column;
  gap: 0.5vh;
  margin-bottom: 1vh;
}

.param-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.param-label {
  color: #cccccc;
  font-size: 0.8vw;
}

.param-value {
  color: #00ff00;
  font-size: 0.8vw;
  font-weight: bold;
}

.result-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.8vh;
}

.result-item {
  text-align: center;
  padding: 0.5vh;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 0.3vh;
  border: 1px solid rgba(0, 245, 255, 0.2);
}

.result-label {
  color: #cccccc;
  font-size: 0.7vw;
  display: block;
  margin-bottom: 0.3vh;
}

.result-value {
  color: #00f5ff;
  font-size: 0.9vw;
  font-weight: bold;
}

:deep(.el-tabs__header) {
  margin: 0 0 1vh 0;
  background: rgba(15, 15, 25, 0.8);
  border-radius: 0.5vh 0.5vh 0 0;
}

:deep(.el-tabs__nav) {
  background: rgba(15, 15, 25, 0.8);
  width: 100%;
  display: flex;
}

:deep(.el-tabs__item) {
  color: #cccccc;
  border-color: rgba(0, 245, 255, 0.3);
  background: rgba(15, 15, 25, 0.6);
  font-size: 0.8vw;
  flex: 1;
  text-align: center;
  justify-content: center;
  margin: 0;
  border-right: 1px solid rgba(0, 245, 255, 0.2);
}

:deep(.el-tabs__item:last-child) {
  border-right: none;
}

:deep(.el-tabs__item.is-active) {
  color: #ffffff;
  background: rgba(0, 245, 255, 0.2);
  border-bottom-color: #00f5ff;
}

:deep(.el-tabs__content) {
  background: rgba(15, 15, 25, 0.8);
  border-radius: 0 0 0.5vh 0.5vh;
  padding: 1vh;
}

:deep(.el-tabs__nav-wrap) {
  background: rgba(15, 15, 25, 0.8);
  width: 100%;
}

:deep(.el-tabs__nav-scroll) {
  width: 100%;
}

:deep(.el-tabs--border-card) {
  background: rgba(15, 15, 25, 0.8);
  border: 1px solid rgba(0, 245, 255, 0.3);
}

:deep(.el-tabs--border-card .el-tabs__header) {
  background: rgba(15, 15, 25, 0.8);
  border-bottom: 1px solid rgba(0, 245, 255, 0.3);
}

:deep(.el-select) {
  width: 8vw;
}

:deep(.el-input__inner) {
  background: rgba(0, 0, 0, 0.5);
  border-color: rgba(0, 245, 255, 0.3);
  color: #ffffff;
  font-size: 0.8vw;
}

/* 自定义滚动条样式 */
.analysis-params::-webkit-scrollbar {
  width: 0.6vw;
}

.analysis-params::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 0.3vw;
}

.analysis-params::-webkit-scrollbar-thumb {
  background: rgba(0, 245, 255, 0.4);
  border-radius: 0.3vw;
}

.analysis-params::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 245, 255, 0.6);
}
</style>